from django.contrib.auth.backends import ModelBackend
import re
from apps.users.models import User
from meiduo_mall.settings.dev import logger
from meiduo_mall.settings import dev
#对邮件中的查询参数进行解密
def check_email_token(token_data):
    #对token中的数据进行解密
    from utils.secret import SecretOauth
    try:
        token_dict = SecretOauth().loads(token_data)
        print(token_dict)
    except Exception as e:
        logger.error(e)
        return None
    #根据token中的数据从数据库中读取对应的用户对象
    try:
        user = User.objects.get(username = token_dict['username'], email = token_dict['email'])
    except Exception as e:
        logger.error(e)
        return None
    return user


#定义生成邮箱验证链接方法
def generate_verify_email_url(user):
    #准备需要加密的数据
    data_dict = {'username': user.username, "email": user.email}

    #对数据进行加密
    from utils.secret import SecretOauth
    secret_data = SecretOauth().dumps(data_dict)

    #返回拼接的url
    active_url = dev.EMAIL_ACTIVE_URL + '?token=' + secret_data
    return active_url

def get_user_by_account(account):
    try:
        if re.match('^1[3-9]\d{9}$',account):
            user = User.objects.get(mobile = account)
        else:
            user = User.objects.get(username = account)
    except Exception as e:
        logger.error(e)
        return None
    else:
        return user

class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user